package com.ruoyi.web.controller.commission;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.attached.domain.Attached;
import com.ruoyi.attached.service.IAttachedService;
import com.ruoyi.attachedData.service.IAttachedDataService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.notice.domain.Notice;
import com.ruoyi.notice.service.INoticeService;
import com.ruoyi.report.domain.Report;
import com.ruoyi.report.service.IReportService;
import com.ruoyi.sample.domain.Sample;
import com.ruoyi.sample.service.ISampleService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import com.ruoyi.task.domain.Task;
import com.ruoyi.task.service.ITaskService;
import com.ruoyi.web.controller.system.SysUserController;
import com.ruoyi.web.controller.task.TaskController;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.commission.domain.Commission;
import com.ruoyi.commission.service.ICommissionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 委托Controller
 *
 * @author ruoyi
 * @date 2025-05-08
 */
@RestController
@RequestMapping("/commission/commission")
public class CommissionController extends BaseController
{
    @Autowired
    private ICommissionService commissionService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISampleService sampleService;

    @Autowired
    private IAttachedService attachedService;

    @Autowired
    private IReportService reportService;

    @Autowired
    private IAttachedDataService attachedDataService;

    @Resource
    private TaskController taskController;

    @Resource
    private SysUserServiceImpl sysUserService;

    @Autowired
    private ITaskService taskService;

    @Autowired
    private INoticeService noticeService;

    @Autowired
    private ISysUserService userService;


    /**
     * 查询委托列表(所有)
     */
    @GetMapping("/listAll")
    public AjaxResult listAll(Commission commission)
    {
        List<Commission> list = commissionService.selectCommissionListAll(commission);
        return AjaxResult.success(list);
    }

    /**
     * 查询委托列表
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:list')")
    @GetMapping("/list")
    public TableDataInfo list(Commission commission)
    {
        //权限 项目经理和实验员 看被分配到的     业主和业主单位看自己单位的
        if(commission.getIsRoleShow() != null && commission.getIsRoleShow() == 1){
            Long userId = SecurityUtils.getLoginUser().getUserId();
            JSONObject jb = userService.getEngineeringIdsForUserId(userId);
            Long enterpriseId = (Long) jb.get("enterpriseId");
            List<Long> engineeringIds = (List<Long>) jb.get("engineeringIds");
            if(enterpriseId != 0){
                commission.setEnterpriseId(enterpriseId);
            }else {
                //项目经理，实验员，劳务实验员
                if (!engineeringIds.isEmpty()) {
                    commission.setIdsList(engineeringIds);
                } else {
                    List<Long> null_ids = new ArrayList<>();
                    null_ids.add(-1L);
                }
            }
        }

        startPage();
        List<Commission> list = commissionService.selectCommissionList(commission);

        return getDataTable(list);
    }

    /**
     * 导出委托列表
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:export')")
    @Log(title = "委托", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Commission commission)
    {
        List<Commission> list = commissionService.selectCommissionList(commission);
        ExcelUtil<Commission> util = new ExcelUtil<Commission>(Commission.class);
        return util.exportExcel(list, "委托数据");
    }

    /**
     * 获取委托详细信息
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(commissionService.selectCommissionById(id));
    }

    /**
     * 新增委托
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:add')")
    @Log(title = "新增委托", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Commission commission) throws ParseException {
        String gc_commission_code=configService.selectConfigByKey("gc_commission_code");
        commission.setTableCode(gc_commission_code);
        commissionService.insertCommission(commission);

        //添加一条任务
        Long id = commission.getId();
        Commission commissionOne = commissionService.selectCommissionById(id);
        Task task = new Task();
        task.setCommissionId(commissionOne.getId());
        task.setEngineeringId(commissionOne.getEngineeringId());
        task.setTaskType("委托受理");
        task.setStatus("0");
        task.setTaskContent(commissionOne.getEnterpriseName() + "对" + commissionOne.getEngineeringName()
                + "的委托单" + commissionOne.getNumber());
        SysUser sysUser = new SysUser();
        sysUser.setRoleId(3L);
        sysUser.setEnterpriseId(commissionOne.getEnterpriseId());
//        sysUser.setDeptId(100L);
        List<SysUser> sysUserList = sysUserService.selectUserList(sysUser);//业务受理员
        if(sysUserList.size() > 1){
            task.setChargePerson(sysUserList.get(0).getUserId().toString());
        }
        taskService.insertTask(task);

        Long userId = getUserId();
        // 消息
        // 委托通知 给 业务受理员
        Notice notice = new Notice();
        notice.setCommissionId(id);
        notice.setEngineeringId(commissionOne.getEngineeringId());
        notice.setNoticType("委托通知");
        notice.setNoticContent(commissionOne.getEnterpriseName()+"对"+commissionOne.getEngineeringName()+"的委托单"+commissionOne.getNumber()+"!");
        if(sysUserList.size() > 1) {
            String notice_userId = userId == 1 ? String.valueOf(userId) : sysUserList.get(0).getUserId().toString();
            notice.setUserId(notice_userId);
        }
        noticeService.insertNotice(notice);

        //签章通知 给 业务受理员
        Notice notice2 = new Notice();
        notice2.setCommissionId(id);
        notice2.setEngineeringId(commissionOne.getEngineeringId());
        notice2.setNoticType("签章通知");
        notice2.setNoticContent(commissionOne.getEnterpriseName()+"对"+commissionOne.getEngineeringName()+"的委托单"+commissionOne.getNumber()+"的文件签章! ");
        if(sysUserList.size() > 1) {
            String notice_userId = userId == 1 ? String.valueOf(userId) : sysUserList.get(0).getUserId().toString();
            notice2.setUserId(notice_userId);
        }
        noticeService.insertNotice(notice2);


        //签章通知 给 委托单位项目员
        SysUser sysUser2 = new SysUser();
        sysUser2.setRoleId(4L);
        sysUser2.setEnterpriseId(commissionOne.getEnterpriseId());
        List<SysUser> sysUserList2 = sysUserService.selectUserList(sysUser2);//委托单位项目员


        Notice notice3 = new Notice();
        notice3.setCommissionId(id);
        notice3.setEngineeringId(commissionOne.getEngineeringId());
        notice3.setNoticType("签章通知");
        notice3.setNoticContent(commissionOne.getEngineeringName()+"的委托单"+commissionOne.getNumber()+"待签章上传！");
        if(sysUserList2.size() > 1){
            String notice_userId = userId == 1 ? String.valueOf(userId) : sysUserList2.get(0).getUserId().toString();
            notice3.setUserId(notice_userId);
        }
        noticeService.insertNotice(notice3);

        return AjaxResult.success(commissionOne);
    }

    /**
     * 修改委托
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:edit')")
    @Log(title = "委托", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Commission commission)
    {
        commission.setUpdateType(DicConstants.BUSINESS_Manager.getCode());
//        commissionService.createExcel(commission.getId(),"D:/file/weituomuban.xlsx","D:/file/weituomuban222.xlsx");
        return toAjax(commissionService.updateCommission(commission));
    }

    /**
     * 删除委托
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:remove')")
    @Log(title = "委托", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(commissionService.logicDeleteCommission(ids,DicConstants.BUSINESS_Manager.getCode(),SecurityUtils.getUserId()));
    }


    /**
     * 受理
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:acceptance')")
    @Log(title = "受理", businessType = BusinessType.UPDATE)
    @PostMapping("/acceptance")
    public AjaxResult acceptance(@RequestBody Commission commission) throws ParseException {
        Integer is_res = commissionService.acceptance(commission);
        return toAjax(is_res);
    }


    //字段回显内容
    @PostMapping("/getDetectionContentChange")
    public AjaxResult getDetectionContentChange(Long commissionId,String businessType )
    {
        //获取detection_content字段回显
        Map comm_map =  commissionService.getDetectionContent(commissionId,businessType);
        return AjaxResult.success(comm_map);
    }

    //废弃
    @PostMapping("/getAttachedInfo")
    public AjaxResult getAttachedInfo(String ids,String businessType )
    {
        Map attachedMap =  attachedService.getInfoAll(ids,businessType);
        return AjaxResult.success(attachedMap);
    }


    @PostMapping("/daoru")
    public AjaxResult daoru(Long commissionId) throws IOException {
        //commissionService.createExcel(commissionId,"D:/file/weituomuban.xlsx","D:/file/weituomuban222.xlsx");
        return AjaxResult.success("dddd");
    }

    //委托单完结
    @PreAuthorize("@ss.hasPermi('commission:commission:updateDone')")
    @PostMapping("/updateDone")
    public AjaxResult updateDone(@RequestParam Long commissionId){
        if(commissionId == null){
            return AjaxResult.error("请传入commissionId参数");
        }
        String res = commissionService.updateDone(commissionId);
        if("委托单已完成".equals(res)){
            return AjaxResult.success(res);
        }else{
            return AjaxResult.error(res);
        }
    }
    @PreAuthorize("@ss.hasPermi('commission:commission:updateDoneTrue')")
    @PostMapping("/updateDoneTrue")
    public AjaxResult updateDoneTrue(@RequestParam Long commissionId) {
        Commission commissionOne = commissionService.selectCommissionById(commissionId);
        if("done".equals(commissionOne.getStatus())){
            return AjaxResult.error("项目已完结，无需重复提交");
        }
        Commission commission = new Commission();
        commission.setId(commissionId);
        commission.setStatus("done");
        Integer isCommission = commissionService.updateCommission(commission);
        return AjaxResult.success("操作成功，项目已完结");
    }
}
